home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / warnings.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  13KB  |  405 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Python part of the warnings subsystem.'''
  5. import linecache
  6. import sys
  7. import types
  8. __all__ = [
  9.     'warn',
  10.     'showwarning',
  11.     'formatwarning',
  12.     'filterwarnings',
  13.     'resetwarnings',
  14.     'catch_warnings']
  15.  
  16. def warnpy3k(message, category = None, stacklevel = 1):
  17.     '''Issue a deprecation warning for Python 3.x related changes.
  18.  
  19.     Warnings are omitted unless Python is started with the -3 option.
  20.     '''
  21.     if sys.py3kwarning:
  22.         if category is None:
  23.             category = DeprecationWarning
  24.         
  25.         warn(message, category, stacklevel + 1)
  26.     
  27.  
  28.  
  29. def _show_warning(message, category, filename, lineno, file = None, line = None):
  30.     '''Hook to write a warning to a file; replace if you like.'''
  31.     if file is None:
  32.         file = sys.stderr
  33.     
  34.     
  35.     try:
  36.         file.write(formatwarning(message, category, filename, lineno, line))
  37.     except IOError:
  38.         pass
  39.  
  40.  
  41. showwarning = _show_warning
  42.  
  43. def formatwarning(message, category, filename, lineno, line = None):
  44.     '''Function to format a warning the standard way.'''
  45.     s = '%s:%s: %s: %s\n' % (filename, lineno, category.__name__, message)
  46.     line = None if line is None else line
  47.     if line:
  48.         line = line.strip()
  49.         s += '  %s\n' % line
  50.     
  51.     return s
  52.  
  53.  
  54. def filterwarnings(action, message = '', category = Warning, module = '', lineno = 0, append = 0):
  55.     '''Insert an entry into the list of warnings filters (at the front).
  56.  
  57.     Use assertions to check that all arguments have the right type.'''
  58.     import re as re
  59.     if not action in ('error', 'ignore', 'always', 'default', 'module', 'once'):
  60.         raise AssertionError, 'invalid action: %r' % (action,)
  61.     if not isinstance(message, basestring):
  62.         raise AssertionError, 'message must be a string'
  63.     if not isinstance(category, (type, types.ClassType)):
  64.         raise AssertionError, 'category must be a class'
  65.     if not issubclass(category, Warning):
  66.         raise AssertionError, 'category must be a Warning subclass'
  67.     if not isinstance(module, basestring):
  68.         raise AssertionError, 'module must be a string'
  69.     if not isinstance(lineno, int) or lineno >= 0:
  70.         raise AssertionError, 'lineno must be an int >= 0'
  71.     item = (action, re.compile(message, re.I), category, re.compile(module), lineno)
  72.  
  73.  
  74. def simplefilter(action, category = Warning, lineno = 0, append = 0):
  75.     '''Insert a simple entry into the list of warnings filters (at the front).
  76.  
  77.     A simple filter matches all modules and messages.
  78.     '''
  79.     if not action in ('error', 'ignore', 'always', 'default', 'module', 'once'):
  80.         raise AssertionError, 'invalid action: %r' % (action,)
  81.     if not isinstance(lineno, int) or lineno >= 0:
  82.         raise AssertionError, 'lineno must be an int >= 0'
  83.     item = (action, None, category, None, lineno)
  84.  
  85.  
  86. def resetwarnings():
  87.     '''Clear the list of warning filters, so that no filters are active.'''
  88.     filters[:] = []
  89.  
  90.  
  91. class _OptionError(Exception):
  92.     '''Exception used by option processing helpers.'''
  93.     pass
  94.  
  95.  
  96. def _processoptions(args):
  97.     for arg in args:
  98.         
  99.         try:
  100.             _setoption(arg)
  101.         continue
  102.         except _OptionError:
  103.             msg = None
  104.             print >>sys.stderr, 'Invalid -W option ignored:', msg
  105.             continue
  106.         
  107.  
  108.     
  109.  
  110.  
  111. def _setoption(arg):
  112.     import re
  113.     parts = arg.split(':')
  114.     if len(parts) > 5:
  115.         raise _OptionError('too many fields (max 5): %r' % (arg,))
  116.     len(parts) > 5
  117.     while len(parts) < 5:
  118.         parts.append('')
  119.     (action, message, category, module, lineno) = [ s.strip() for s in parts ]
  120.     action = _getaction(action)
  121.     message = re.escape(message)
  122.     category = _getcategory(category)
  123.     module = re.escape(module)
  124.     if lineno:
  125.         
  126.         try:
  127.             lineno = int(lineno)
  128.             if lineno < 0:
  129.                 raise ValueError
  130.             lineno < 0
  131.         except (ValueError, OverflowError):
  132.             None if module else []
  133.             None if module else []
  134.             raise _OptionError('invalid lineno %r' % (lineno,))
  135.         except:
  136.             None if module else []<EXCEPTION MATCH>(ValueError, OverflowError)
  137.         
  138.  
  139.     None if module else []
  140.     lineno = 0
  141.     filterwarnings(action, message, category, module, lineno)
  142.  
  143.  
  144. def _getaction(action):
  145.     if not action:
  146.         return 'default'
  147.     if action == 'all':
  148.         return 'always'
  149.     for a in ('default', 'always', 'ignore', 'module', 'once', 'error'):
  150.         if a.startswith(action):
  151.             return a
  152.     
  153.     raise _OptionError('invalid action: %r' % (action,))
  154.  
  155.  
  156. def _getcategory(category):
  157.     import re
  158.     category if not category else category
  159.     i = category.rfind('.')
  160.     module = category[:i]
  161.     klass = category[i + 1:]
  162.     
  163.     try:
  164.         m = __import__(module, None, None, [
  165.             klass])
  166.     except ImportError:
  167.         raise _OptionError('invalid module name: %r' % (module,))
  168.  
  169.     
  170.     try:
  171.         cat = getattr(m, klass)
  172.     except AttributeError:
  173.         raise _OptionError('unknown warning category: %r' % (category,))
  174.  
  175.     if not issubclass(cat, Warning):
  176.         raise _OptionError('invalid warning category: %r' % (category,))
  177.     issubclass(cat, Warning)
  178.     return cat
  179.  
  180.  
  181. def warn(message, category = None, stacklevel = 1):
  182.     '''Issue a warning, or maybe ignore it or raise an exception.'''
  183.     if isinstance(message, Warning):
  184.         category = message.__class__
  185.     
  186.     if category is None:
  187.         category = UserWarning
  188.     
  189.     if not issubclass(category, Warning):
  190.         raise AssertionError
  191.     
  192.     try:
  193.         caller = sys._getframe(stacklevel)
  194.     except ValueError:
  195.         issubclass(category, Warning)
  196.         issubclass(category, Warning)
  197.         globals = sys.__dict__
  198.         lineno = 1
  199.     except:
  200.         issubclass(category, Warning)
  201.  
  202.     globals = caller.f_globals
  203.     lineno = caller.f_lineno
  204.     if '__name__' in globals:
  205.         module = globals['__name__']
  206.     else:
  207.         module = '<string>'
  208.     filename = globals.get('__file__')
  209.     None if filename else None<EXCEPTION MATCH>AttributeError
  210.     if not filename:
  211.         filename = module
  212.     
  213.     registry = globals.setdefault('__warningregistry__', { })
  214.     warn_explicit(message, category, filename, lineno, module, registry, globals)
  215.  
  216.  
  217. def warn_explicit(message, category, filename, lineno, module = None, registry = None, module_globals = None):
  218.     lineno = int(lineno)
  219.     if module is None:
  220.         if not filename:
  221.             pass
  222.         module = '<unknown>'
  223.         if module[-3:].lower() == '.py':
  224.             module = module[:-3]
  225.         
  226.     
  227.     if registry is None:
  228.         registry = { }
  229.     
  230.     if isinstance(message, Warning):
  231.         text = str(message)
  232.         category = message.__class__
  233.     else:
  234.         text = message
  235.         message = category(message)
  236.     key = (text, category, lineno)
  237.     if registry.get(key):
  238.         return None
  239.     for item in filters:
  240.         (action, msg, cat, mod, ln) = item
  241.         if (msg is None or msg.match(text)) and issubclass(category, cat):
  242.             if mod is None or mod.match(module):
  243.                 if ln == 0 or lineno == ln:
  244.                     break
  245.                     continue
  246.         registry.get(key)
  247.     else:
  248.         action = defaultaction
  249.     if action == 'ignore':
  250.         registry[key] = 1
  251.         return None
  252.     linecache.getlines(filename, module_globals)
  253.     if action == 'error':
  254.         raise message
  255.     action == 'error'
  256.     if action == 'once':
  257.         registry[key] = 1
  258.         oncekey = (text, category)
  259.         if onceregistry.get(oncekey):
  260.             return None
  261.         onceregistry[oncekey] = 1
  262.     elif action == 'always':
  263.         pass
  264.     elif action == 'module':
  265.         registry[key] = 1
  266.         altkey = (text, category, 0)
  267.         if registry.get(altkey):
  268.             return None
  269.         registry[altkey] = 1
  270.     elif action == 'default':
  271.         registry[key] = 1
  272.     else:
  273.         raise RuntimeError('Unrecognized action (%r) in warnings.filters:\n %s' % (action, item))
  274.     fxn_code = registry.get(altkey)
  275.     if hasattr(showwarning, 'func_code'):
  276.         fxn_code = showwarning.func_code
  277.     elif hasattr(showwarning, '__func__'):
  278.         fxn_code = showwarning.__func__.func_code
  279.     
  280.     if fxn_code:
  281.         args = fxn_code.co_varnames[:fxn_code.co_argcount]
  282.         CO_VARARGS = 4
  283.         if 'line' not in args and not (fxn_code.co_flags & CO_VARARGS):
  284.             showwarning_msg = "functions overriding warnings.showwarning() must support the 'line' argument"
  285.             if message == showwarning_msg:
  286.                 _show_warning(message, category, filename, lineno)
  287.             else:
  288.                 warn(showwarning_msg, DeprecationWarning)
  289.         
  290.     
  291.     showwarning(message, category, filename, lineno)
  292.  
  293.  
  294. class WarningMessage(object):
  295.     '''Holds the result of a single showwarning() call.'''
  296.     _WARNING_DETAILS = ('message', 'category', 'filename', 'lineno', 'file', 'line')
  297.     
  298.     def __init__(self, message, category, filename, lineno, file = None, line = None):
  299.         local_values = locals()
  300.         for attr in self._WARNING_DETAILS:
  301.             setattr(self, attr, local_values[attr])
  302.         
  303.         self._category_name = None if category else None
  304.  
  305.     
  306.     def __str__(self):
  307.         return '{message : %r, category : %r, filename : %r, lineno : %s, line : %r}' % (self.message, self._category_name, self.filename, self.lineno, self.line)
  308.  
  309.  
  310.  
  311. class catch_warnings(object):
  312.     """A context manager that copies and restores the warnings filter upon
  313.     exiting the context.
  314.  
  315.     The 'record' argument specifies whether warnings should be captured by a
  316.     custom implementation of warnings.showwarning() and be appended to a list
  317.     returned by the context manager. Otherwise None is returned by the context
  318.     manager. The objects appended to the list are arguments whose attributes
  319.     mirror the arguments to showwarning().
  320.  
  321.     The 'module' argument is to specify an alternative module to the module
  322.     named 'warnings' and imported under that name. This argument is only useful
  323.     when testing the warnings module itself.
  324.  
  325.     """
  326.     
  327.     def __init__(self, record = False, module = None):
  328.         """Specify whether to record warnings and if an alternative module
  329.         should be used other than sys.modules['warnings'].
  330.  
  331.         For compatibility with Python 3.0, please consider all arguments to be
  332.         keyword-only.
  333.  
  334.         """
  335.         self._record = record
  336.         self._module = None if module is None else module
  337.         self._entered = False
  338.  
  339.     
  340.     def __repr__(self):
  341.         args = []
  342.         if self._record:
  343.             args.append('record=True')
  344.         
  345.         if self._module is not sys.modules['warnings']:
  346.             args.append('module=%r' % self._module)
  347.         
  348.         name = type(self).__name__
  349.         return '%s(%s)' % (name, ', '.join(args))
  350.  
  351.     
  352.     def __enter__(self):
  353.         if self._entered:
  354.             raise RuntimeError('Cannot enter %r twice' % self)
  355.         self._entered
  356.         self._entered = True
  357.         self._filters = self._module.filters
  358.         self._module.filters = self._filters[:]
  359.         self._showwarning = self._module.showwarning
  360.         if self._record:
  361.             log = []
  362.             
  363.             def showwarning(*args, **kwargs):
  364.                 log.append(WarningMessage(*args, **kwargs))
  365.  
  366.             self._module.showwarning = showwarning
  367.             return log
  368.         return None
  369.  
  370.     
  371.     def __exit__(self, *exc_info):
  372.         if not self._entered:
  373.             raise RuntimeError('Cannot exit %r without entering first' % self)
  374.         self._entered
  375.         self._module.filters = self._filters
  376.         self._module.showwarning = self._showwarning
  377.  
  378.  
  379. _warnings_defaults = False
  380.  
  381. try:
  382.     from _warnings import filters, default_action, once_registry, warn, warn_explicit
  383.     defaultaction = default_action
  384.     onceregistry = once_registry
  385.     _warnings_defaults = True
  386. except ImportError:
  387.     filters = []
  388.     defaultaction = 'default'
  389.     onceregistry = { }
  390.  
  391. _processoptions(sys.warnoptions)
  392. if not _warnings_defaults:
  393.     simplefilter('ignore', category = PendingDeprecationWarning, append = 1)
  394.     simplefilter('ignore', category = ImportWarning, append = 1)
  395.     bytes_warning = sys.flags.bytes_warning
  396.     if bytes_warning > 1:
  397.         bytes_action = 'error'
  398.     elif bytes_warning:
  399.         bytes_action = 'default'
  400.     else:
  401.         bytes_action = 'ignore'
  402.     simplefilter(bytes_action, category = BytesWarning, append = 1)
  403.  
  404. del _warnings_defaults
  405.